from dao.company_dao import CompanyDao
from model.company import Company
import math


class CompanyService:
    def __init__(self, session):
        self.session = session

    def add(self, company):
        dao = CompanyDao(self.session)
        dao.add(company)

    def get_by_uuid(self, uuid):
        dao = CompanyDao(self.session)
        return dao.get_by_uuid(uuid)

    def merge(self, company):
        dao = CompanyDao(self.session)
        dao.merge(company)

    def get_by_company_id_detail(self, company_id):
        dao = CompanyDao(self.session)
        return dao.get_by_company_id_detail(company_id)

    def get_by_company_id(self, company_id):
        dao = CompanyDao(self.session)
        return dao.get_by_company_id(company_id)

    def get_by_name(self, name):
        dao = CompanyDao(self.session)
        return dao.get_by_name(name)

    def get_list(self, **kwargs):
        q = self.session.query(Company)
        total = q.count()
        page_size = kwargs.get('page_size', 10)
        page = kwargs.get('page', 1)
        res = q.offset((page - 1) * page_size).limit(page_size).all()
        records = []
        for data in res:
            records.append(data.json())
        return {'list': records,
                'total': total,
                "cur_page": page,
                "total_page": math.ceil(total / page_size)}


if __name__ == '__main__':
    from utils.work_db import Session

    session = Session()
    cservice = CompanyService(session)
    data = cservice.get_list()
    print(data)
